package redisinit

import (
	"cart/cart"
	"context"
	"fmt"
	"strconv"
)

func AddCart(userId, goodsId, goodsNum int, goodsName string, goodsPrice float64) error {
	key := fmt.Sprintf("cart:user_id_%d:goods_id_%d", userId, goodsId)
	return RedisClient.HMSet(context.Background(), key, map[string]interface{}{
		"goodsId":    goodsId,
		"goodsName":  goodsName,
		"goodsNum":   goodsNum,
		"goodsPrice": goodsPrice,
		"checked":    1,
	}).Err()

}
func ListCart(userId int) (CartList []*cart.CartInfo) {
	key := fmt.Sprintf("cart:user_id_%d:*", userId)
	keys := RedisClient.Keys(context.Background(), key).Val()
	for _, v := range keys {
		goodsInfo := RedisClient.HGetAll(context.Background(), v).Val()
		goodsId, _ := strconv.Atoi(goodsInfo["goodsId"])
		goodsNum, _ := strconv.Atoi(goodsInfo["goodsNum"])
		goodsName := goodsInfo["goodsName"]
		goodsPrice, _ := strconv.ParseFloat(goodsInfo["goodsPrice"], 64)
		CartList = append(CartList, &cart.CartInfo{
			UserId:     int64(userId),
			GoodsId:    int64(goodsId),
			GoodsName:  goodsName,
			GoodsPrice: float32(goodsPrice),
			GoodsNum:   int64(goodsNum),
		})
	}
	return
}
